package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 工作提醒 信息操作处理
 *
 * @author ruoyi
 * @date 2019-09-04
 */
@Controller
@RequestMapping("/system/ncWorkNotice")
public class NcWorkNoticeController extends BaseController {
	private String prefix = "system/ncWorkNotice";

	@Autowired
	private INcWorkNoticeService ncWorkNoticeService;

	@Autowired
	private INcCowsDisinfectionService ncCowsDisinfectionser;

	@Autowired
	private INcYaoClassService yaoClassService;

	@Autowired
	private INcCowsFilesService ncCowsFilesService;

	@Autowired
	private INcCowsMilkService ncCowsMilkService;

	@Autowired
	private INcFeedLogService ncFeedLogService;

	@Autowired
	private INcMeterialService ncMeterialService;

	@Autowired
	private INcFeedService ncFeedService;

	@RequiresPermissions("system:ncWorkNotice:view")
	@GetMapping()
	public String ncWorkNotice() {
		return prefix + "/ncWorkNotice";
	}

	//工作提醒
	@GetMapping("/ncadd")
	public String ncadd() {
		return prefix + "/ncadd";
	}


	/**
	 * 查询工作提醒列表
	 */
	@RequiresPermissions("system:ncWorkNotice:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(NcWorkNotice ncWorkNotice) {
		startPage();
		List<NcWorkNotice> list = ncWorkNoticeService.selectNcWorkNoticeList(ncWorkNotice);
		return getDataTable(list);
	}


	/**
	 * 导出工作提醒列表
	 */
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(NcWorkNotice ncWorkNotice) {
		List<NcWorkNotice> list = ncWorkNoticeService.selectNcWorkNoticeList(ncWorkNotice);
		ExcelUtil<NcWorkNotice> util = new ExcelUtil<NcWorkNotice>(NcWorkNotice.class);
		return util.exportExcel(list, "ncWorkNotice");
	}

	/**
	 * 新增工作提醒
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存工作提醒
	 */
	@RequiresPermissions("system:ncWorkNotice:add")
	@Log(title = "工作提醒", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(NcWorkNotice ncWorkNotice) {
		ncWorkNotice.setNoticeType(1);

		//根据worktype插入工作名称
		if (ncWorkNotice.getWorkType() == 1) {
			ncWorkNotice.setWorckNoticeName("消毒");
		} else if (ncWorkNotice.getWorkType() == 2) {
			ncWorkNotice.setWorckNoticeName("喂料");
		} else if (ncWorkNotice.getWorkType() == 3) {
			ncWorkNotice.setWorckNoticeName("挤奶");
		} else {
			return AjaxResult.error("请选择工作名称");
		}

		return toAjax(ncWorkNoticeService.insertNcWorkNotice(ncWorkNotice));
	}

	/**
	 * 修改工作提醒
	 */
	@GetMapping("/edit/{workNoticeId}")
	public String edit(@PathVariable("workNoticeId") Long workNoticeId, ModelMap mmap) {
		NcWorkNotice ncWorkNotice = ncWorkNoticeService.selectNcWorkNoticeById(workNoticeId);
		mmap.put("ncWorkNotice", ncWorkNotice);
		return prefix + "/edit";
	}

	/**
	 * 修改保存工作提醒
	 */
	@RequiresPermissions("system:ncWorkNotice:edit")
	@Log(title = "工作提醒", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(NcWorkNotice ncWorkNotice) {
		//根据worktype修改工作名称
		if (ncWorkNotice.getWorkType() == 1) {
			ncWorkNotice.setWorckNoticeName("消毒");
		} else if (ncWorkNotice.getWorkType() == 2) {
			ncWorkNotice.setWorckNoticeName("喂料");
		} else if (ncWorkNotice.getWorkType() == 3) {
			ncWorkNotice.setWorckNoticeName("挤奶");
		} else {
			return AjaxResult.error("请选择工作名称");
		}
		return toAjax(ncWorkNoticeService.updateNcWorkNotice(ncWorkNotice));
	}

	/**
	 * 删除工作提醒
	 */
	@RequiresPermissions("system:ncWorkNotice:remove")
	@Log(title = "工作提醒", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(ncWorkNoticeService.deleteNcWorkNoticeByIds(ids));
	}

	/**
	 * 消毒记录    system:ncGoods:disinfection
	 * 消毒      disinfection
	 */
	@RequiresPermissions("system:ncGoods:disinfection")
	@Log(title = "农事", businessType = BusinessType.INSERT)
	@GetMapping("/disinfection/{workNoticeId}")
	public String disinfection(@PathVariable("workNoticeId") Long workNoticeId, ModelMap mmap) {
		NcWorkNotice disinfection = ncWorkNoticeService.selectNcWorkNoticeById(workNoticeId);
		mmap.put("disinfection", disinfection);

		return prefix + "/disinfection";
	}

	/**
	 * 消毒记录保存    system/ncWorkNotice/disinfection
	 */
	@Log(title = "消毒管理", businessType = BusinessType.INSERT)
	@PostMapping("/disinfection")
	@ResponseBody
	public AjaxResult addSave(NcCowsDisinfection ncCowsDisinfection) {
		SysUser sysUser = ShiroUtils.getSysUser();
		ncCowsDisinfection.setDfUser(sysUser.getLoginName());
		//设置管理类型 牛舍 为2
		ncCowsDisinfection.setManagerType(2);

		//根据yao_id查找药品批次 ncCowsDisinfection.getYaoId()
		NcYaoClass ncYaoClass = yaoClassService.selectYaoClassById(ncCowsDisinfection.getYaoId());

		ncCowsDisinfection.setDfCode(ncYaoClass.getCode());

		//消毒结束将消毒时间放到最后修改时间
		NcWorkNotice ncWorkNotice = new NcWorkNotice();
		ncWorkNotice.setLastTime(ncCowsDisinfection.getDfDate());
		ncWorkNotice.setWorkNoticeId(ncCowsDisinfection.getWorkNoticeId());
		ncWorkNoticeService.updateNcWorkNotice(ncWorkNotice);

		return toAjax(ncCowsDisinfectionser.insertNcCowsDisinfection(ncCowsDisinfection));
	}

	/**
	 * 挤奶操作
	 */
	@RequiresPermissions("system:ncGoods:milk")
	@Log(title = "农事", businessType = BusinessType.INSERT)
	@GetMapping("/milk/{workNoticeId}")
	public String milk(@PathVariable("workNoticeId") Long workNoticeId, ModelMap mmap) {
		NcWorkNotice milk = ncWorkNoticeService.selectNcWorkNoticeById(workNoticeId);
		mmap.put("milk", milk);

		List<NcCowsFiles> ncCowsFilesList = ncCowsFilesService.selectNcCowsFilesAll();
		mmap.put("ncCowsFiles", ncCowsFilesList);
		return prefix + "/milk";

	}

	/**
	 * 挤奶提交
	 */
	@Log(title = "挤奶提交", businessType = BusinessType.INSERT)
	@PostMapping("/milk")
	@ResponseBody
	public AjaxResult addSave(NcCowsMilk milk) {

		for (Map<String, String> milkMilk : milk.getMilks()) {
			for (Map.Entry<String, String> m : milkMilk.entrySet()) {
				if (m.getKey().equals("id")) {
					milk.setCowId(Integer.parseInt(m.getValue()));
					continue;
				}
				if (m.getKey().equals("value")) {
					if (StringUtils.isNotEmpty(m.getValue())) {
						milk.setMilkAmount(BigDecimal.valueOf(Double.parseDouble(m.getValue())));
						milk.setCreateTime(new Date()); //时间
						SysUser sysUser = ShiroUtils.getSysUser();
						milk.setCreateBy(1+"");//创建人
                        //通过worknotic查找时段
                        NcWorkNotice ncWorkNotice = ncWorkNoticeService.selectNcWorkNoticeById(milk.getWorkNoticeId());
                        if (ncWorkNotice.getTime().compareTo("8") >-1) {
                            milk.setTimeStage(1); //时段
                        }else {
                            milk.setTimeStage(2); //时段
                        }
						ncCowsMilkService.insertNcCowsMilk(milk);
					}

				}
			}
		}

		//设置最后操作时间
		NcWorkNotice ncWorkNotice = new NcWorkNotice();
		ncWorkNotice.setLastTime(new Date());
		ncWorkNotice.setWorkNoticeId(milk.getWorkNoticeId());
		ncWorkNoticeService.updateNcWorkNotice(ncWorkNotice);


		return AjaxResult.success("插入成功");
	}

	/**
	 * 饲喂操作
	 */
	@RequiresPermissions("system:ncGoods:feed")
	@Log(title = "农事", businessType = BusinessType.INSERT)
	@GetMapping("/feed/{workNoticeId}")
	public String feed(@PathVariable("workNoticeId") Long workNoticeId, ModelMap mmap) {
		mmap.put("feed", ncWorkNoticeService.selectNcWorkNoticeById(workNoticeId));

		NcFeed feed1 = new NcFeed();
		feed1.setFeedType(1);
		feed1.setManagerType(2);
		mmap.put("meterial",ncFeedService.selectNcFeedList(feed1));

		NcFeed feed=new NcFeed();
		feed.setFeedType(2);
		feed.setManagerType(2);
		mmap.put("meterial1",ncFeedService.selectNcFeedList(feed));

		return prefix + "/feed";
	}

	/**
	 * 饲喂提交
	 */
	@Log(title = "饲喂提交", businessType = BusinessType.INSERT)
	@PostMapping("/feed")
	@ResponseBody
	public AjaxResult addSave(NcFeedLog feedLog) {


		Map feedes = feedLog.getFeedes();
		NcFeedLog ncFeedLog = new NcFeedLog();
		if(feedes.get("z_feedName")!=null){
			//通过feedId获取库存
			NcFeed feed = ncFeedService.selectNcFeedById(Long.parseLong(feedes.get("z_feedName")+"") );
//			if (feed.getStockAmout() >= Integer.parseInt(feedes.get("z_num")+"")) {

			if(feedes.get("z_num") != null && feedes.get("z_num") !=""){
				BigDecimal z_num = BigDecimal.valueOf(Double.parseDouble(feedes.get("z_num") + ""));
				if (feed.getStockAmout().compareTo(BigDecimal.valueOf(Double.parseDouble(feedes.get("z_num")+"")))>-1) {


					ncFeedLog.setFeedId(Long.parseLong(feedes.get("z_feedName")+"") );
//				ncFeedLog.setOutputAmount(Integer.parseInt(feedes.get("z_num")+"") );
					ncFeedLog.setOutputAmount(BigDecimal.valueOf(Double.parseDouble(feedes.get("z_num")+"")));
					ncFeedLog.setFeedType(1);
					//设置时间
					ncFeedLog.setCreateTime(new Date());


					if (Double.parseDouble(feedes.get("z_num")+"") >=0) {
						ncFeedLogService.insertNcFeedLog(ncFeedLog);
						feed.setStockAmout(feed.getStockAmout().subtract(BigDecimal.valueOf(Double.parseDouble(feedes.get("z_num")+""))));	//设置出库后库存
						ncFeedService.updateNcFeed(feed);
					}else {
						return AjaxResult.error("不能为负数");
					}


				}else {
					return AjaxResult.error("主饲料库存不足");
				}
			}
//

		}

		if(feedes.get("f_feedName")!=null){
			NcFeed feed1 = ncFeedService.selectNcFeedById(Long.parseLong(feedes.get("z_feedName")+"") );
			NcFeed feed = ncFeedService.selectNcFeedById(Long.parseLong(feedes.get("f_feedName")+"") );
//			if (feed.getStockAmout() >= Integer.parseInt(feedes.get("f_num")+"")) {
			if(feedes.get("f_num")!=null && feedes.get("f_num")!=""){
				if (feed.getStockAmout().compareTo(BigDecimal.valueOf(Double.parseDouble(feedes.get("f_num") + "")))>-1) {

					ncFeedLog.setFeedId(Long.parseLong(feedes.get("f_feedName")+""));
//				ncFeedLog.setOutputAmount(Integer.parseInt(feedes.get("f_num")+""));
					ncFeedLog.setOutputAmount(BigDecimal.valueOf(Double.parseDouble(feedes.get("f_num") + "")));
					ncFeedLog.setFeedType(2);

//				feed.setStockAmout(feed.getStockAmout() - Integer.parseInt(feedes.get("f_num")+""));	//设置出库后库存
					if (Double.parseDouble(feedes.get("f_num") + "")>=0) {
						ncFeedLogService.insertNcFeedLog(ncFeedLog);
						feed.setStockAmout(feed.getStockAmout().subtract(BigDecimal.valueOf(Double.parseDouble(feedes.get("f_num") + ""))));	//设置出库后库存

						ncFeedService.updateNcFeed(feed);
					}else{

						return AjaxResult.error("不能为负数");
					}

				} else {
					ncFeedLogService.deleteNcFeedLogByIds(String.valueOf(ncFeedLog.getFeedLogId()));
					feed1.setStockAmout(feed1.getStockAmout().add(BigDecimal.valueOf(Double.parseDouble(feedes.get("z_num") + ""))));	//设置出库后库存
					ncFeedService.updateNcFeed(feed1);
					return AjaxResult.error("辅饲料库存不足");
				}
			}



		}

		//设置最后操作时间
		NcWorkNotice ncWorkNotice = new NcWorkNotice();
		ncWorkNotice.setLastTime(new Date());
		ncWorkNotice.setWorkNoticeId(feedLog.getWorkNoticeId());
		ncWorkNoticeService.updateNcWorkNotice(ncWorkNotice);

		return AjaxResult.success("成功");
	}
}
